//
//  MYVideoLoadingAlertView.m
//  MiaoYin
//
//  Created by DarkWorld on 2021/11/22.
//  Copyright © 2021 thy. All rights reserved.
//

#import "MYVideoLoadingAlertView.h"
#import <AliyunVideoSDKPro/AliyunVodPublishManager.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "MYPublishAliVideoViewController.h"

@interface MYVideoLoadingAlertView ()<AliyunIExporterCallback>
/// 主视图
@property(nonatomic, strong) UIView *mainView;
@property(nonatomic, strong) UILabel *progressLabel;
//上传控制
@property(nonatomic, strong) AliyunVodPublishManager *publishManager;
/**
 出现特定错误，重新合成的次数
 */
@property(nonatomic, assign) NSInteger errorReExportCount;

@end
@implementation MYVideoLoadingAlertView
- (AliyunVodPublishManager *)publishManager{
    if (!_publishManager) {
        _publishManager =[[AliyunVodPublishManager alloc]init];
        _publishManager.exportCallback = self;
    }
    return _publishManager;
}
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];

        [self initData];
        [self initView];

    }
    return self;
}

- (void)dealloc
{
}

#pragma mark - Intial Methods
/**
 初始化数据
 */
- (void)initData
{
}

/**
 初始化试图
 */
- (void)initView
{
    [self addMainView];
}
- (void)addMainView
{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.8];
    [self addSubview:view];
    view.layer.cornerRadius = 8;
    view.layer.masksToBounds = YES;
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self);
        make.width.mas_equalTo(152);
        make.height.mas_equalTo(152);
    }];
    self.mainView = view;

    UIImage *image = UIImageMake(@"shortVideo_Edit_Camer");
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    [self.mainView addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mainView).offset(38);
        make.centerX.equalTo(self.mainView);
        make.size.mas_equalTo(CGSizeMake(50, 50));
    }];
    
    UILabel *label = [[UILabel alloc] init];
    label.font = [UIFont systemFontOfSize:13];
    label.textColor = [UIColor whiteColor];
    label.text = @"视频合成中…0%";
    [self.mainView addSubview:label];
    self.progressLabel = label;
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(imageView.mas_bottom).offset(8);
        make.centerX.equalTo(self.mainView);
    }];
    
    
    
}
- (void)exportVideo{
   int result = [self.publishManager exportWithTaskPath:_taskPath outputPath:_config.outputPath];
    if (result != 0) {
        [self showAlertWithTitle:@"合成失败" message:@"合成失败,请返回重试" ];
    }
   
    
}
- (void)showAlertWithTitle:(NSString *)title message:(NSString *)message{
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertController *alertController =[UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action =[UIAlertAction actionWithTitle:@"确定"  style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:action];
        [self.cureentVC presentViewController:alertController animated:YES completion:nil];
    });
}

- (UIImage *)thumbnailWithVideoPath:(NSString *)videoPath
                         outputSize:(CGSize)outputSize {
    AVURLAsset *asset =
    [AVURLAsset assetWithURL:[NSURL fileURLWithPath:videoPath]];
    AVAssetImageGenerator *_generator =
    [[AVAssetImageGenerator alloc] initWithAsset:asset];
    _generator.maximumSize = outputSize;
    _generator.appliesPreferredTrackTransform = YES;
    _generator.requestedTimeToleranceAfter = kCMTimeZero;
    _generator.requestedTimeToleranceBefore = kCMTimeZero;
    CMTime time = CMTimeMake(0 * 1000, 1000);
    CGImageRef image = [_generator copyCGImageAtTime:time
                                          actualTime:NULL
                                               error:nil];
    UIImage *picture = [UIImage imageWithCGImage:image];
    CGImageRelease(image);
    return picture;
}

#pragma mark - export callback
- (void)exportProgress:(float)progress {
    DLog(@"进度值progress：%f",progress);
    self.progressLabel.text = [NSString stringWithFormat:@"视频合成中…%.0f%%",progress*100];

}

- (void)exporterDidCancel {
    NSLog(@"export cancel");
    //合成结束，开启侧滑返回
   
}

- (void)exporterDidStart {
    //开始合成禁用侧滑返回
}

- (void)exportError:(int)errorCode {
    NSLog(@"export error");
    if (errorCode == 268447759) {
        //退后台导致的上一次错误 - 重新开始合成
        if (_errorReExportCount > 5) {
            [self showExportError:errorCode];
        } else {
            [self.publishManager cancelExport];
            [self exportVideo];
            _errorReExportCount++;
        }
        return;
    }
    [self.publishManager cancelExport];
    [self showExportError:errorCode];
    
}

- (void)showExportError:(int)errorCode {
    //正常合成失败
    [self dismiss];

    [self showAlertWithTitle:@"合成失败"  message:[NSString stringWithFormat:@"Error Code:%d",
                                                  errorCode]];
}

- (void)exporterDidEnd:(NSString *)outputPath {
    [self dismiss];

    if (_coverImage == nil) {
        _coverImage = [self thumbnailWithVideoPath:_config.outputPath outputSize:_outputSize];
        
    }
    
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    [library writeVideoAtPathToSavedPhotosAlbum:[NSURL fileURLWithPath:_config.outputPath] completionBlock:^(NSURL *assetURL, NSError *error) {
         NSLog(@"视频已保存到相册");
     }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)),
                   dispatch_get_main_queue(), ^{
        MYPublishAliVideoViewController *vc = [[MYPublishAliVideoViewController alloc] init];
        vc.taskPath = self.taskPath;
        vc.config = self.config;
        if (self.coverImage) {
            vc.coverImage = self.coverImage;

        }
        
        vc.outputSize = _config.outputSize;
        vc.draft = self.draft;
        
        [self.cureentVC.navigationController pushViewController:vc animated:YES];

    });
    if (self.finishBlock) {
        self.finishBlock(outputPath);
    }
}

#pragma mark - Lazy Loads
- (void)show
{

    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self];
    self.mainView.top = self.height;
    [UIView animateWithDuration:0.25 animations:^{
        self.mainView.top = 0;
    }];
}
- (void)dismiss
{
    self.mainView.backgroundColor = [UIColor clearColor];

    [UIView animateWithDuration:0.25 animations:^{
        self.mainView.top = self.height;

    } completion:^(BOOL finished) {

        [self removeFromSuperview];
     
        
    }];
    
}



@end
